package com.by.service.sys.impl;

import com.by.entity.sys.Dept;
import com.by.entity.sys.DeptBean;
import com.by.mapper.sys.DeptMapper;
import com.by.service.sys.DeptService;
import com.by.utils.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DeptServiceImpl implements DeptService {

    @Autowired(required = false)
    DeptMapper deptMapper;


    @Autowired(required = false)
    JdbcTemplate jdbcTemplate;

    @Override
    public List<Dept> query(String pid) {
        return deptMapper.queryChild(pid);
    }

    @Override
    public int save(DeptBean deptBean) {
        //根据父id查询最大编码
        String maxCode = deptMapper.queryMaxCodeByParentId(deptBean.getParentId());
        if (StringUtils.isEmpty(maxCode) && !"0".equals(deptBean.getParentId())) {
            //查询上级部门的编码
            String code = deptMapper.queryDeptCode(deptBean.getParentId());
            deptBean.setCode(code + "01");
        } else {
            deptBean.setCode(generateNextCode(maxCode));
        }
        return deptMapper.save(deptBean);
    }


    @Override
    public List<Dept> queryChildByCode(String code) {
        return deptMapper.queryChildByCode(code);
    }

    @Override
    public List queryAllChild(String pid) {
        Map map=new HashMap();
        map.put("pid",pid);
        map.put("_rs","");
        deptMapper.queryAllChild(map);
        ObjectMapper objectMapper=new ObjectMapper();
       List list=null;
        try {
             list=  objectMapper.readValue(map.get("_rs").toString(),List.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 根据已有编码生成下一个编码
     *
     * @param code
     * @return
     */
    String generateNextCode(String code) {
        if (null == code || "".equals(code)) {
            //说明是第一个编码
            return "101";
        }

        //获取编码长度  10101
        int len = code.length();
        //如果编码存在 截取
        String prefix = code.substring(0, len - 2);
        String seq = code.substring(len - 2);
        //将序列seq转换成数字
        int num = Integer.parseInt(seq);
        num++;
        return prefix + String.format("%02d", num);
    }

    @Override
    public int update(DeptBean deptBean) {
        return 0;
    }

}
